import {take,call,put,select} from 'redux-saga/effects'
import {get, post, put_http} from '../axios'
import {actionsTypes as IndexActionTypes} from '../reducers'
import {actionsTypes as SActionTypes} from '../reducers/schedule'
import history from '../history';

export function* get_list () {
    yield put({type: IndexActionTypes.FETCH_START});
    try {
        return yield call(get, `/mem/project-progress`);
    } catch (err) {
        yield put({type: IndexActionTypes.SET_MESSAGE, msgContent: '网络请求错误', msgType: 'fail'});
    } finally {
        yield put({type: IndexActionTypes.FETCH_END})
    }
}

export function* getScheduleListFlow () {
    while (true){
        let req = yield take(SActionTypes.GET_MILESTONE);
        let res = yield call(get_list);
        if(res){
            if (res.current_page) {
                yield put({type: SActionTypes.RES_MILESTONE, data: res})
            } else {
                yield put({type: IndexActionTypes.SET_MESSAGE, msgContent: res.msg, msgType: 'fail'});
            }
        }
    }
}

export function* save_schedule (data, project_id, id) {
    yield put({type: IndexActionTypes.FETCH_START});
    try {
        if (id) {
            return yield call(put_http, `/mem/project-progress/${id}`, data);
        } else {
            return yield call(post, `/mem/project-progress/${project_id}`, data);
        }
    } catch (err) {
        yield put({type: IndexActionTypes.SET_MESSAGE, msgContent: '网络请求错误', msgType: 'fail'});
    } finally {
        yield put({type: IndexActionTypes.FETCH_END})
    }
}

export function* saveScheduleFlow () {
    while (true){
        let req = yield take(SActionTypes.SAVE_SCHEDULE);
        let project_id = req.project_id? req.project_id : undefined
        console.log(req.data)
        let res = yield call(save_schedule, req.data, project_id);
        if (res&&res.success) {
            yield put({type: IndexActionTypes.SET_MESSAGE, msgContent: '操作成功', msgType: 'success'});
           
            yield call( ()=>setTimeout( function () {
                history.goBack()
            }, 1000))
        } else {
            yield put({type: IndexActionTypes.SET_MESSAGE, msgContent: res.msg, msgType: 'fail'});
        }
    }
}